<template>
  <div class="virtual-list"  @scroll="onScroll">
    <div class="virtual-list-content" :style="{ height: totalHeight + 'px' }">
      <div v-for="(item, index) in listData" :key="item.id"
        :style="{ height: itemHeight + 'px', transform: `translateY(${offsetY}px)` }" class="virtual-list-item">
        <slot :item="item" :index="index"></slot>
      </div>
    </div>
  </div>
</template>


<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import http from '@/http/axios'
const pagecode = ref(0)
const listData = ref([])
// https://www.chunyuyisheng.com/cooperation/wap/health_news/
// 请求接口
async function GetList() {
  const resp = await http.get('/static/cooperation/wap/health_news/', {
    params: {
      from_wx_mini: '1',
      page: pagecode.value,
      partner: 'chunyu_wap_mini',
      release_time: '2020-04-22%2010%3A30%3A00',
      channel_id: '0'
    }
  })
  console.log(resp.data.content_list);
  listData.value = [...listData.value, ...resp.data.content_list]
}
GetList()

const props = defineProps({
  items: {
    type: Array,
    required: true,
  },
  itemHeight: {
    type: Number,
    default: 0,
  },
  itemComponent: {
    type: Object,
    required: true,
  },
});

const listContainer = ref(null);
const startIndex = ref(0);
const visibleCount = ref(0);
const offsetY = ref(0);
const totalHeight = computed(() => props.items.length * props.itemHeight);
// 计算可见项目的数量
const calculateVisibleCount = () => {
  const container = listContainer.value;
  if (container) {
    const containerHeight = container.clientHeight;
    visibleCount.value = Math.ceil(containerHeight / props.itemHeight);
  }
};




//计算科技项目索引范围

//滚动处理
const onScroll = () => {
  const container = listContainer.value;
  if (container) {
    const scrollTop = container.scrollTop;
    startIndex.value = Math.floor(scrollTop / props.itemHeight) + 1;
  }
};

// 组件挂载时计算可见项目数
onMounted(() => {
  calculateVisibleCount();
  window.addEventListener('resize', calculateVisibleCount);
});

//清理资源
onUnmounted(() => {
  window.removeEventListener('resize', calculateVisibleCount);
});



</script>

<style scoped>
.virtual-list {
  overflow-y: auto;
  height: 600px;
  /* 设定固定高度 */
  position: relative;
}

.virtual-list-content {
  position: relative;
}

.virtual-list-item {
  box-sizing: border-box;
  height: 60px;
  line-height: 80px;
  /* 与 itemHeight 相同 */
  padding: 0 10px;
}
</style>